﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MakeItWeb.Framework;
using System.Data;
using System.Configuration;

namespace AllNations
{
    /// <summary>
    /// Summary description for FileShareDownload
    /// </summary>
    public class FileShareDownload : IHttpHandler
    {

        private string GetExtension(string sFilename)
        {
            return sFilename.Substring(sFilename.LastIndexOf('.'));
        }

        public void ProcessRequest(HttpContext context)
        {
            Guid guidFileshareId = new Guid(context.Request.QueryString["FileshareId"]);
            StoredProcArgs args = new StoredProcArgs();
            args["pFileshareId"] = guidFileshareId;
            using (DataSet ds = GenericQry.GetDataSet("proc_cm_GetFileshare", args))
            {
                if (ds.Tables[0].Rows.Count > 0)
                {
                    DataRow dr = ds.Tables[0].Rows[0];
                    string sFilename = string.Format(@"{0}\{1}\{2}{3}",
                        context.Server.MapPath(ConfigurationManager.AppSettings["FileshareRoot"]),
                        dr["html_page_id"],
                        dr["fileshare_id"],
                        GetExtension(dr["filename_txt"].ToString()));

                    byte[] bytesFile = System.IO.File.ReadAllBytes(sFilename);

                    context.Response.Expires = 0;
                    context.Response.ContentType = dr["content_type"].ToString();
                    context.Response.AddHeader("Content-Length", bytesFile.Length.ToString());
                    context.Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", dr["filename_txt"]));
                    context.Response.BinaryWrite(bytesFile);
                    context.Response.End();
                }
            }
            context.Response.ContentType = "text/plain";
            context.Response.Write("Invalid request!");
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}